import { INodeInputSlot, INodeOutputSlot, LGraphNode, LLink } from "litegraph.js";
import { CpcBase, ICpcBaseIos } from "../base/CpcBase";
import { CpcDrawerCtrl, ICpcDrawerConfig } from "../../../../components/CpcDrawer/CpcDrawerCtrl";
import { LitegraphUtils } from "../../utils/LitegraphUtils";

const ios: ICpcBaseIos = {
    inputs: [
        {
            name: "inputSource",
            type: "Object",
            label: "输入的对象",
        },
    ],
    outputs: [],
};

export class ObjectTo extends CpcBase {
    public title = "拆分对象";

    public desc = "拆分对象";

    public type = "ObjectTo";

    protected codeEditDbShow = true;

    protected codeEidtReadOnly = true;

    constructor(title?: string) {
        super(ios, title);
        this.addWidget("button", "编辑输出节点", "", this.clickAdd.bind(this));
    }

    clickAdd() {
        const self = this;
        CpcDrawerCtrl.open(
            {
                component: "AEBasicField",
                data: this.getOutputsNot0(),
                callBack(data: any, close: any) {
                    self.updateOutputsNot0(data);
                    close();
                },
            },
            {
                title: "编辑输出节点",
                styleType: "center",
                isMaskEvent: false,
            }
        );
    }

    public onCpcConnectInput(slotIndex: number, link: LLink, ioSlot: INodeOutputSlot | INodeInputSlot) {
        if (slotIndex > 0) {
            const outputNode = this.graph?.getNodeById(link.origin_id);
            if (outputNode instanceof CpcBase) {
                const datas = outputNode.cpcRun(true);
                if (datas && datas.length >= slotIndex) {
                    const data = datas[slotIndex - 1];
                    Object.keys(data).forEach(key => {
                        this.addOutput(key, LitegraphUtils.checkType(data[key]));
                    });
                }
            }
        }
    }

    public onCpcDisConnectInput(slotIndex: number, link: LLink, ioSlot: INodeOutputSlot | INodeInputSlot) {
        if (slotIndex > 0) {
            this.removeOutputsNot0();
        }
    }

    cpcRunCode(preDatas: any[], inputInfos: any[], outputInfos: any[]): any[] {
        const data = preDatas[0];
        if (!data) {
            return [];
        }
        return outputInfos.map(item => {
            return data[item.name];
        });
    }
}
